<?php

namespace Authentication\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Authentication\Form\LoginForm;

class AuthenticationController extends AbstractActionController {
    public function loginAction() {
        $messages = null;
        $form = $this->getLoginForm();
        
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                
                $authData = $form->getData();
                
                $authAdapter = $this->getAuthenticationAdapter();
                $authAdapter->setIdentity($authData['login']);
                $authAdapter->setCredential($authData['password']);
      
                $authService = $this->getAuthenticationService();
                $result = $authService->authenticate();
                
                if($result->isValid()) {
                    return $this->redirect()->toRoute('home');
                } 
                
                $messages = $result->getMessages();
            } 
            
            $this->flashMessenger()
                    ->setNamespace('Authentication\Controller\AuthenticationController')
                    ->addMessage('Login failed!'); 
        }
        
        
        return array('form' => $form, 'messages' => $messages); 
    } 
    
    public function logoutAction() {
        $authService = $this->getAuthenticationService();
        $authService->clearIdentity();
        return $this->redirect()->toRoute('home');
    } 
    
    /**
     * @return \Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter
     */
    protected function getAuthenticationAdapter() {
        return $this->getServiceLocator()->get('Authentication\Service\AuthenticationAdapter');
    }
    
    /**
     * @return AuthenticationService
     */
    protected function getAuthenticationService() {
        return $this->getServiceLocator()->get('Authentication\Service\AuthenticationService');
    }
    
    /**
     * @return LoginForm
     */
    protected function getLoginForm() {
        return $this->getServiceLocator()->get('Authentication\Form\LoginForm');
    }
}